package com.jboost.modules.app.service.strategry.dp;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jboost.common.util.DateUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.BaseResult;
import com.jboost.modules.app.dto.JdyReq;
import com.jboost.modules.app.service.strategry.common.AbstractJdy;
import com.jboost.modules.system.entity.DpDingdan;
import com.jboost.modules.system.mapper.DpDingdanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service(value = "DpDingdanTimeQuery")
@Slf4j
public class DpDingdanTimeQuery extends AbstractJdy<String, DpDingdan, DpDingdanMapper, DpDingdan> {


    public String getFormId() {
        return "63f0bcda3d300400077367af";
    }

    public String getFormId1() {
        return "63f0bcda3d300400077367af";
    }

    public HttpHeaders getJdyHeaders() {
        HttpHeaders jdyHeaders = new HttpHeaders();
        jdyHeaders.set("Authorization", "Bearer " + "bdfDElitwqhraWZoCv3uxdv9PysCV605");
        return jdyHeaders;
    }

    public String getAppId() {
        return "64880dc1f3ecc50008fbae61";
    }


    @Scheduled(initialDelay = 1000, fixedRate = 60000)
    @Async
    public BaseResult<Boolean> invokeStrategy() throws Exception {
        DpDingdan hxProduct = new DpDingdan();
        sync(hxProduct);
        return BaseResult.success();
    }

    public void sync(DpDingdan entit) throws IOException, ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        log.info("开始批量查询Hs材料数据");
        JdyReq jdyReq = new JdyReq();
        jdyReq.setApp_id(getAppId());
        jdyReq.setEntry_id(getFormId());
        jdyReq.setLimit(100);
        jdyReq.setFields(Arrays.asList("_widget_1676727862897","_id","create_date","createTime","creator","username","platform_id"));
        JdyReq.FilterBean filterBean = new JdyReq.FilterBean();
        filterBean.setRel("and");
        List<JdyReq.FilterBean.CondBean> cond = new ArrayList<>();
        JdyReq.FilterBean.CondBean a = new JdyReq.FilterBean.CondBean();
        a.setField("createTime");
        a.setMethod("range");
        a.setValue(Arrays.asList(DateUtils.formatDate(org.apache.commons.lang3.time.DateUtils.addHours(new Date(),-30), "yyyy-MM-dd HH:mm:ss"),DateUtils.formatDate(org.apache.commons.lang3.time.DateUtils.addHours(new Date(),128), "yyyy-MM-dd HH:mm:ss")));
        cond.add(a);
        filterBean.setCond(cond);
        jdyReq.setFilter(filterBean);
        String s = jdyQueryAll(jdyReq);
        JSONArray jsonArray = (JSONArray) JSONUtil.fromJson(s, HashMap.class).get("data");
        if (jsonArray.size() > 0) {
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                String id = jsonObject.getString("_id");
                String time = jsonObject.getString("create_date");
                JSONObject creator = jsonObject.getObject("creator", JSONObject.class);
                Date date = dateFormat.parse(time);
                Date date8 = org.apache.commons.lang3.time.DateUtils.addHours(date, -8);
                String username = creator.getString("name");
                String platform_id = jsonObject.getString("platform_id");
                String _widget_1676727862897 = jsonObject.getString("_widget_1676727862897");
                if (StringUtils.isNotBlank(_widget_1676727862897)){
                    continue;
                }
                Map map = new HashMap();
                if (Objects.equals(username,"东品美业") && "shopify/亚马逊/ebay".contains(platform_id)) {
                    map.put("_widget_1676727862897",getParaMap(dateFormat.format(date8)));
                } else {
                    map.put("_widget_1676727862897",getParaMap(dateFormat.format(date)));
                }
                jdyUpdate(id,map);
            }
        }

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        invokeStrategy();
    }


//    public void sync(DpDingdan pdmPl) throws IOException {
//        log.info("开始批量查询Hs材料数据");
//        //baseMapper.delete((Wrapper<PdmPl>) Wrappers.lambdaQuery(entit.getClass()).orderByDesc(BaseEntity::getId).ne(BaseEntity::getId,"0"));
//        HashMap<String, Object> param = getParam();
//        param.put("limit",1000);
//        List<JSONObject> jsonObjects = new ArrayList<>();
//        do {
//            String post = HttpRestUtils.post(query_all_api, param, getJdyHeaders());
//            jsonObjects   = (List<JSONObject>) JSONUtil.fromJson(post, Map.class).get("data");
//            jsonObjects.forEach(e -> {
//                try {
//                    Object o = baseMapper.selectById(e.getString("_id"));
//
//                    if (Objects.isNull(o)) {
//                        baseMapper.insert(pdmPl);
//                    }else if (!Objects.equals(o,pdmPl)){
//                        baseMapper.deleteById(pdmPl.getId());
//                        baseMapper.insert(pdmPl);
//                    }
//                }catch (Exception exception){
//
//                }
//
//            });
//            if (jsonObjects.size()>0){
//
//                param.put("data_id",jsonObjects.get(jsonObjects.size()-1).getString("_id"));
//            }
//        }while (jsonObjects.size()>0);
//
//    }
}
